package net.nagaseyasuhito.nicola.component;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.model.IModel;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.validator.AbstractValidator;

public class ImageUploadField extends FileUploadField {
	private static final long serialVersionUID = 1L;

	public ImageUploadField(String id) {
		super(id);
		this.initialize();
	}

	public ImageUploadField(String id, IModel model) {
		super(id, model);
		this.initialize();
	}

	private void initialize() {
		this.add(new AbstractValidator() {
			private static final long serialVersionUID = 1L;

			@Override
			protected void onValidate(IValidatable validatable) {
				try {
					BufferedImage image = ImageIO.read(new ByteArrayInputStream(ImageUploadField.this.getFileUpload().getBytes()));
					
					if(image == null) {
						throw new IOException();
					}
				}
				catch(IllegalArgumentException e) {
					this.error(validatable, "invalidImage");
				}
				catch(IOException e) {
					this.error(validatable, "invalidImage");
				}
			}
		});
	}

	@Override
	public void updateModel() {
		if(this.getFileUpload() != null) {
			this.setModelObject(this.getFileUpload().getBytes());
		}
	}
}
